package com.nineclock.auth.processor.impl;

import cn.hutool.core.util.StrUtil;
import com.nineclock.auth.entity.IntegrationAuthenticationEntity;
import com.nineclock.auth.processor.AuthenticationProcessor;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 短信验证码的认证方式
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Component
public class SmsAuthenticationProcessor implements AuthenticationProcessor {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    SysUserFeign userFeign;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public SysUserDTO authenticate(IntegrationAuthenticationEntity entity) {
        //获取手机号和验证码
        String mobile = entity.getAuthParameter("mobile");
        String password = entity.getAuthParameter("password");
        if(StrUtil.isEmpty(mobile) || StrUtil.isEmpty(password)){
            throw new NcException(ResponseEnum.INVALID_USERNAME_PASSWORD);
        }

        SysUserDTO userDTO = userFeign.queryUser(mobile).getData();
        if(userDTO == null){
            throw new NcException(ResponseEnum.USER_NOT_FOUND);
        }

        //更改密码（应该是从redis数据库中获取 的密码）
        String key = SMSConstant.SMS_LOGIN_KEY_PREFIX + mobile;
        //获取验证码
        String code = redisTemplate.boundValueOps(key).get();
        //把验证码加密后存储到 userDTO
        userDTO.setPassword(passwordEncoder.encode(code));

        return userDTO;
    }

    /**
     * 是否支持此认证方式
     * @param entity
     * @return
     */
    @Override
    public boolean support(IntegrationAuthenticationEntity entity) {
        if(entity != null && "sms".equals(entity.getAuthType())){
            return true;
        }
        return false;
    }
}
